//
//  LKScrollView.m
//  Travel
//
//  Created by tixa tixa on 13-4-23.
//  Copyright (c) 2013年 tixa. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "LKScrollView.h"

#import "NSString+Category.h"
//#import "ASIHTTPRequest.h"
//#import "TKProgressCircleView.h"
#import "LKImageManager.h"


#define duration 0.4

@interface LKScrollView ()
{
    UIScrollView *contentScrollView;
    float width;
    float height;
    float scale;
    CGSize mainSize;
    float fileLength;
    
    UITapGestureRecognizer *doubleTapGR;
    UITapGestureRecognizer *tapGR;
    
    NSString *dealImageURL;
    UIImage  *dealImage;
    BOOL isDownload;
    BOOL isWidthImage;
    
//    ASIHTTPRequest *httpRequest;
//    TKProgressCircleView *progressBar;//进度条视图
    UILabel   *progressLabel;//进度条标签
    UIView *loadingView;
    NSMutableData *receivedData;//下载原图过程中的已接收数据
    
    NSString *_downloadFileDir;//原图下载保存目录 默认 @"Documents/ImageCache"
    
    CGRect oldFrame;
    
    UIButton *_menuButton;
}
@end

@implementation LKScrollView

+ (id)scrollViewWithImageView:(LKImageView *)imageView
{
    return [[self alloc] initWithImageView:imageView];
}

- (id)initWithImageView:(LKImageView *)imageView
{
    self = [super init];
    if (self) {
        _imageView = imageView;
        oldFrame = _imageView.frame;
        
        mainSize = [UIScreen mainScreen].bounds.size;
        scale = 2.0;
        _downloadFileDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/ImageCache"];
        
        self.frame = CGRectMake(0, 0, mainSize.width, mainSize.height);
        
        contentScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, mainSize.width, mainSize.height)];
        contentScrollView.delegate = self;
        [contentScrollView addSubview:_imageView];
        
        [self addSubview:contentScrollView];
        
        UIImage *saveImage  = [UIImage imageNamed:@"TIXAImage_save_image.png"];
        _menuButton = [[UIButton alloc] initWithFrame:CGRectMake(mainSize.width - 69, mainSize.height - 40, 59, 30)];
        [_menuButton setImage:saveImage forState:UIControlStateNormal];
        _menuButton.hidden = YES;
        [_menuButton addTarget:self action:@selector(saveImage) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_menuButton];
        
        
        //添加手势
        doubleTapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapImage)];
        doubleTapGR.numberOfTapsRequired = 2;
        doubleTapGR.numberOfTouchesRequired = 1;
        [contentScrollView addGestureRecognizer:doubleTapGR];
        
        tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(quitFullScreen)];
        tapGR.numberOfTapsRequired = 1;
        tapGR.numberOfTouchesRequired = 1;
        [tapGR requireGestureRecognizerToFail:doubleTapGR];//遇到双击事件时，屏蔽单击事件
        [contentScrollView addGestureRecognizer:tapGR];
    }
    return self;
}

/*存储图片到相册*/
- (void)saveImage
{
	if (dealImage != nil) {
		UIImageWriteToSavedPhotosAlbum(dealImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
	}
}

/*存储结果提示*/
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
	if (error == nil) {
//		[[TKAlertCenter defaultCenter] postAlertWithMessage:@"已存储到相册" image:[UIImage imageNamed:@"image_save.png"]];
	} else {
//		[[TKAlertCenter defaultCenter] postAlertWithMessage:@"存储失败"];
	}
}

- (void)enterFullScreen:(BOOL)animated
{
    CGFloat factor = 1;//图片宽高比参数
    if (_imageView.image != nil) {
        factor = _imageView.image.size.width / _imageView.image.size.height;
    }
    CGFloat x;
    CGFloat y;
    if (factor > mainSize.width/mainSize.height) {//图片属于宽图，宽调整为320.0
        width  = mainSize.width;
        height = mainSize.width/factor;
        x = 0.0;
        y = mainSize.height/2 - height/2.0;
    } else {//图片属于高图，高调整为480.0
        width  = mainSize.width;
        height = mainSize.width/factor;
        x = mainSize.width/2 - width/2.0;
        y = 0.0;
    }
    
    _imageView.center = _manager.touchPoint;
    
    if (animated) {
        [UIView animateWithDuration:duration animations:^{
            _imageView.frame = CGRectMake(x, y, width, height);
        }];
    } else {
        _imageView.frame = CGRectMake(x, y, width, height);
    }
}

//退出全屏
- (void)quitFullScreen
{
    [_menuButton removeFromSuperview];
    _menuButton = nil;
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationNone];
    
    [contentScrollView removeGestureRecognizer:doubleTapGR];
    [contentScrollView removeGestureRecognizer:tapGR];
    [self cancelLoadImage];
    if (_manager == nil) {
        [_imageView removeFromSuperview];
        _imageView = nil;
        [contentScrollView removeFromSuperview];
        contentScrollView.delegate = nil;
        contentScrollView = nil;
        [self.superview removeFromSuperview];
        return;
    }
    int i_x = self.tag % _manager.column;
    int i_y = self.tag / _manager.column;
    int t_x = _manager.touchIndex % _manager.column;
    int t_y = _manager.touchIndex / _manager.column;
    
    CGPoint point = CGPointMake(_manager.touchPoint.x, _manager.touchPoint.y - 10.0);
    
    float off_y = 10.5;
    
    float temp_x =  point.x - oldFrame.size.width/2 + contentScrollView.contentOffset.x;
    if (i_x != t_x) {
        temp_x += (i_x - t_x) * (oldFrame.size.width + _manager.edge);
    }
    float temp_y =  point.y - oldFrame.size.height/2 + contentScrollView.contentOffset.y + off_y;
    if (i_y != t_y) {
        temp_y += (i_y - t_y) * (oldFrame.size.height + _manager.edge);
    }

    self.superview.backgroundColor = [UIColor clearColor];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    if (_manager.corner) {
        _imageView.layer.cornerRadius = _manager.corner;
    }  
    [UIView animateWithDuration:duration animations:^{
        _imageView.frame = CGRectMake(temp_x, temp_y, oldFrame.size.width, oldFrame.size.height);
    } completion:^(BOOL finished) {
        [_imageView removeFromSuperview];
        _imageView = nil;
        [contentScrollView removeFromSuperview];
        contentScrollView.delegate = nil;
        contentScrollView = nil;
        [_manager removeScrollView];
    }];
}

- (void)dealloc
{
//    NSLog(@"dealloc %d", self.tag);
    [self cancelLoadImage];
}

- (BOOL)isLoading
{
//    return [httpRequest isExecuting];
    
    return NO;
}

- (void)cancelLoadImage
{
    [self removeDownloadView];
    
//    if ([httpRequest isExecuting]) {
//        [httpRequest clearDelegatesAndCancel];
//    }
//    httpRequest.delegate = nil;
//    httpRequest = nil;
}

//加载图片
- (void)loadImage
{
    //存储原图图片
    NSString *filePath = nil;
    if (_imageView.originalImage == nil) {
        if (_imageView.originalURL.length) {
            filePath = [_downloadFileDir stringByAppendingPathComponent:_imageView.originalURL.GBKEncodedString];
            dealImageURL = _imageView.originalURL;
            _imageView.originalImage = [UIImage imageWithContentsOfFile:filePath];
        }
    }
    dealImage = _imageView.originalImage;
    if (dealImage == nil) {//加载原图
        if (_imageView.normalImage == nil) {//加载中图 模式
            if (_imageView.normalURL.length) {
                filePath = [_downloadFileDir stringByAppendingPathComponent:_imageView.normalURL.GBKEncodedString];
                _imageView.normalImage = [UIImage imageWithContentsOfFile:filePath];
            }
        }
        dealImage = _imageView.normalImage;
        if (dealImage == nil) { //没有中图缓存
            if (_imageView.normalURL.length) { //没有中图下载路径
                dealImageURL = _imageView.normalURL;
            } else { //没有中图下载路径 则去查找原图路径
                if (_imageView.originalURL.length) {
                    filePath = [_downloadFileDir stringByAppendingPathComponent:_imageView.originalURL.GBKEncodedString];
                    dealImageURL = _imageView.originalURL;
                } else {
                    filePath = nil;
                }
            }
        }
    } 
    
    isDownload = NO;
    if (dealImage == nil) {//未下载过图片,异步加载
        NSLog(@"begin download");
        if (filePath.length) {
            isDownload = YES;
            [self downloadImage:filePath];
        }
    } else {//下载过图片,从文件加载
        contentScrollView.maximumZoomScale = scale;
        contentScrollView.minimumZoomScale = 0.5;
        [self performSelector:@selector(showImage) withObject:nil afterDelay:0.1];//延迟加载,解决读取特大图时的卡顿
    }
}

- (void)downloadImage:(NSString *)filePath
{
    //判断filePath 路径的目录是否存在 不存在 则创建
    NSString *directoryPath = [filePath substringToIndex:filePath.length - [(NSString *)filePath.pathComponents.lastObject length]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
	if (![fileManager fileExistsAtPath:directoryPath]) {
		[fileManager createDirectoryAtPath:directoryPath withIntermediateDirectories:YES attributes:nil error:nil];
	}
    if (dealImageURL.isValidImageURL) {
        [self downloadOriginalRequest:filePath];
    } else {
        [self downloadNormalRequest:filePath];
    }
}

//中图请求下载
- (void)downloadNormalRequest:(NSString *)filePath
{
//    if (!loadingView) {
//        loadingView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 100.0, 100.0)];
//        loadingView.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
//        loadingView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.5];
//        loadingView.layer.cornerRadius = 6.0;
//        
//        UIActivityIndicatorView *activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//        activityIndicatorView.center = CGPointMake(50, 50);
//        [loadingView addSubview:activityIndicatorView];
//        [activityIndicatorView startAnimating];
//        
//        [self addSubview:loadingView];
//        
//        if ([httpRequest isExecuting]) {
//            [httpRequest clearDelegatesAndCancel];
//            httpRequest = nil;
//        }
//        
//        httpRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:dealImageURL]];
//        httpRequest.delegate = self;
//        [httpRequest setDownloadDestinationPath:filePath];
//        [httpRequest setTimeOutSeconds:300];//设置超时时间为30s
//        [httpRequest startAsynchronous];
//    }
}

//原图请求下载
- (void)downloadOriginalRequest:(NSString *)filePath
{
//    if (!progressBar) {
//        //添加进度条
//        progressBar = [[TKProgressCircleView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
//        progressBar.center = CGPointMake(mainSize.width/2, mainSize.height/2);
//        [self addSubview:progressBar];
//        //添加进度条进度显示的标签
//        progressLabel = [[UILabel alloc] initWithFrame:CGRectMake(mainSize.width/2 - 60, mainSize.height/2 + 20, 120, 20)];
//        progressLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.75];
//        progressLabel.layer.cornerRadius = 8;
//        progressLabel.text = @"正在下载...";
//        progressLabel.textColor = [UIColor whiteColor];
//        progressLabel.textAlignment = UITextAlignmentCenter;
//        [self addSubview:progressLabel];
//        
//        if ([httpRequest isExecuting]) {
//            [httpRequest clearDelegatesAndCancel];
//            httpRequest = nil;
//        }
//        NSLog(@"dealImageURL===%@",dealImageURL);
//        httpRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:dealImageURL]];
//        httpRequest.delegate = self;
//        [httpRequest setDownloadDestinationPath:filePath];
//        [httpRequest setTimeOutSeconds:300];//设置超时时间为30s
//        [httpRequest setDownloadProgressDelegate:self];//设置进度条
//        [httpRequest startAsynchronous];
//    }
}

//取消下载请求
- (void)removeDownloadView
{
//    [progressBar removeFromSuperview];
//    progressBar = nil;
    [progressLabel removeFromSuperview];
    progressLabel = nil;
    [loadingView removeFromSuperview];
    loadingView = nil;
}

/*******
 视图管理
 *******/
/*显示原图*/
- (void)showImage
{
	contentScrollView.multipleTouchEnabled = YES;
    //分为“宽图”、“高图”两种类型处理
    CGFloat factor = dealImage.size.width / dealImage.size.height;//图片宽高比参数
    CGFloat x;
    CGFloat y;
    if (factor > mainSize.width/mainSize.height) {//图片属于宽图，宽调整为320.0
        width = mainSize.width;
        height = mainSize.width/factor;
        x = 0.0;
        y = mainSize.height/2 - height/2.0;
        isWidthImage = YES;
    } else {//图片属于高图，高调整为480.0
        width = mainSize.width;
        height = mainSize.width/factor;
        x = 0.0;//mainSize.width/2 - width/2.0;
        y = 0.0;
        contentScrollView.contentSize = CGSizeMake(width, height);
        isWidthImage = NO;
    }
    
    _imageView.frame = CGRectMake(x, y, width, height);
    _imageView.image = dealImage;
    
    _menuButton.hidden = NO;
}

/***********************
 ASIHTTPRequest delegate
 ***********************/
/*下载失败*/
//- (void)requestFailed:(ASIHTTPRequest *)request
//{
//	NSLog(@"下载失败: %@", request.error);
//    dealImage = _imageView.image;
//    [self removeDownloadView];
//}
//
///*下载完成*/
//- (void)requestFinished:(ASIHTTPRequest *)request
//{
//    NSLog(@"requestFinished");
//    [self removeDownloadView];
//    
//    if (dealImageURL.length) {
//        NSString *filePath = [_downloadFileDir stringByAppendingPathComponent:dealImageURL.GBKEncodedString];
//        dealImage = [UIImage imageWithContentsOfFile:filePath];
//    }
//    
//	if (dealImage != nil) {
//		contentScrollView.maximumZoomScale = scale;
//		contentScrollView.minimumZoomScale = 0.5;
//		[self showImage];
//	}
//}
//
///*请求得到响应，从头部获取图片信息*/
//- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
//{
//    if (fileLength == 0) {
//        fileLength = request.contentLength/1024.0/1024.0;
//    }
//}

- (void)setProgress:(float)newProgress
{
//    progressBar.progress = newProgress;
    if (fileLength > 0) {
        progressLabel.text = [NSString stringWithFormat:@"%.2fM/%.2fM", fileLength * newProgress, fileLength];
    }
}


/*双击屏幕，放大图片到4倍或恢复原图大小*/
- (void)doubleTapImage
{
	if (dealImage != nil) {//图片加载成功
		//判定触摸点是否在图片内部
        CGPoint point = [doubleTapGR locationInView:_imageView];//获取触摸点相对于image的坐标
        float tempX = _imageView.frame.size.width;
        float tempY = _imageView.frame.size.height;
        
        float pointX = point.x * contentScrollView.zoomScale;
        float pointY = point.y * contentScrollView.zoomScale;
        
        if (pointX > 0.0 && pointY > 0.0 && pointX < tempX && pointY < tempY) {
            if (contentScrollView.zoomScale >= scale) {//当前图片已经最大化
                [contentScrollView zoomToRect:[self getRectWithScale:1 andCenter:point] animated:YES];
            } else {//当前图片未最大化
                [contentScrollView zoomToRect:[self getRectWithScale:scale andCenter:point] animated:YES];
            }
        }
	}
}

- (CGRect)getRectWithScale:(float)scale1 andCenter:(CGPoint)center
{
    CGRect rect;
    rect.size.width = contentScrollView.frame.size.width/scale1;
    rect.size.height = contentScrollView.frame.size.height/scale1;
    rect.origin.x = center.x - rect.size.width/2;
    rect.origin.y = center.y - rect.size.height/2;
    return rect;
}

- (void)recoverDoubleView
{
    if (contentScrollView.zoomScale >= scale) {
        CGPoint point = CGPointMake(contentScrollView.frame.size.width, contentScrollView.frame.size.height);
        [contentScrollView zoomToRect:[self getRectWithScale:1 andCenter:point] animated:YES];
    }
}

/*******************
 scrollView delegate
 *******************/
/*返回放缩对象*/
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
	return _imageView;
}

/*缩放过程控制*/
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
	//根据相对原图放大和缩小两种情况，定位图片位置
    
    if(scrollView.zoomScale <= 1.0) {
        CGFloat tempX = 0.0;
        CGFloat tempY = 0.0;
        CGFloat tempW = width * scrollView.zoomScale;
        CGFloat tempH = height * scrollView.zoomScale;
        if (tempW <= mainSize.width) {
            tempX = mainSize.width/2 - tempW/2.0;
        } else {
            tempX = 0;
        }
        
        if (tempH <= mainSize.height) {
            tempY = mainSize.height/2 - tempH/2.0;
        } else {
            tempY = 0;
        }
        _imageView.frame = CGRectMake(tempX, tempY, tempW, tempH);
    } else {
        CGFloat tempX = 0.0;
        CGFloat tempY = 0.0;
        CGFloat tempW = width * scrollView.zoomScale;
        CGFloat tempH = height * scrollView.zoomScale;
        
        if (isWidthImage) {
            if (tempW >= mainSize.width) {
                tempX = 0.0;
            } else {
                tempX = mainSize.width/2 - tempW/2.0;
            }
            
            if (tempH >= mainSize.height) {
                tempY = 0.0;
            } else {
                tempY = mainSize.height/2 - tempH/2.0;
            }
        }
        _imageView.frame = CGRectMake(tempX, tempY, tempW, tempH);
    }
}

/*缩放结束后的操作*/
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)atScale
{
    if (atScale < 1.0) {
        CGPoint point = CGPointMake(contentScrollView.frame.size.width, contentScrollView.frame.size.height);
        [contentScrollView zoomToRect:[self getRectWithScale:1 andCenter:point] animated:YES];
    }
}


@end
